from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.utils import timezone

class Role(models.Model):
    name = models.CharField('角色名称', max_length=50, unique=True)
    code = models.CharField('角色代码', max_length=50, unique=True)
    description = models.TextField('角色描述', null=True, blank=True)
    permissions = models.JSONField('权限配置', default=dict)
    is_system = models.BooleanField('是否系统角色', default=False)
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '角色'
        verbose_name_plural = verbose_name
        ordering = ['created_at']

    def __str__(self):
        return self.name

class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError('用户名必须提供')
        if not extra_fields.get('email'):
            raise ValueError('邮箱必须提供')
            
        # 检查是否是第一个用户
        is_first_user = self.model.objects.count() == 0
        
        # 设置默认值
        if is_first_user:
            extra_fields['is_superuser'] = True
            extra_fields['is_staff'] = True
            extra_fields['is_admin'] = True
        else:
            extra_fields.setdefault('is_staff', False)
            extra_fields.setdefault('is_superuser', False)
            extra_fields.setdefault('is_admin', False)
        
        extra_fields.setdefault('is_active', True)
        
        user = self.model(username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_admin', True)
        extra_fields.setdefault('is_active', True)
        
        if not extra_fields.get('email'):
            raise ValueError('超级管理员必须提供邮箱')
            
        return self.create_user(username, password, **extra_fields)

class User(AbstractUser):
    GENDER_CHOICES = (
        ('M', '男'),
        ('F', '女'),
    )
    
    # 基本信息
    username = models.CharField('用户名', max_length=150, unique=True)
    name = models.CharField('姓名', max_length=50)
    email = models.EmailField('邮箱', unique=True)
    gender = models.CharField('性别', max_length=1, choices=GENDER_CHOICES)
    phone = models.CharField('手机号', max_length=11, null=True, blank=True)
    role = models.ForeignKey(Role, verbose_name='角色', on_delete=models.SET_NULL, null=True, blank=True)
    
    # 状态信息
    is_active = models.BooleanField('是否启用', default=True)
    is_admin = models.BooleanField('是否管理员', default=False)
    is_staff = models.BooleanField('是否工作人员', default=False)
    is_superuser = models.BooleanField('是否超级管理员', default=False)
    
    # 登录信息
    ip_address = models.GenericIPAddressField('IP地址', null=True, blank=True)
    login_count = models.IntegerField('登录次数', default=0)
    last_login = models.DateTimeField('最后登录时间', null=True, blank=True)
    
    # 时间信息
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['name', 'email', 'gender']

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name}({self.username})"
        
    def get_role_display(self):
        if self.is_superuser and self.is_staff and self.is_admin:
            return '超级管理员'
        elif self.is_admin:
            return '管理员'
        else:
            return '普通用户'
